/*
 * 广播处理器
 * 作者：成绍勇
 * 2015-11-9
 */
package cn.lcfms.utils;

import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.RemoteEndpoint.Basic;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import net.sf.json.JSONObject;


@ServerEndpoint("/websocket/getPlagConnct")
public class FlagWebsocket {
	private static HashSet<Session> session=new HashSet<>();
 
    @OnOpen
    public void start(Session session) throws InterruptedException, IOException{ 
    	FlagWebsocket.session.add(session);
    	System.out.println("仿站用户启动广播");
    }
 
    @OnMessage
    public void process(Session session, String message) throws IOException{
    	
    }
 
 
    @OnClose
    public void end(Session session) throws IOException{       
        System.out.println("仿站用户退出广播");
        if(FlagWebsocket.session.contains(session)) {
        	  FlagWebsocket.session.remove(session);
        }     
    }
 
    @OnError
    public void error(Session session, java.lang.Throwable throwable) throws IOException{
        end(session);
    }
    
    public static void echo(Boolean success,String msg,double step){
    	JSONObject object=new JSONObject();
    	object.put("step", step);
    	object.put("msg", msg);
    	object.put("success", success);
    	Iterator<Session> iterator = session.iterator();
    	while(iterator.hasNext()) {
    		Session next = iterator.next();
    		Basic remote = next.getBasicRemote();
    		try {
    			remote.sendText(object.toString());
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }
}